import {defineStore} from "pinia";
import type {LoginParams} from "@/api/user/types";
import {login} from "@/api/user";
import {setToken} from "@/utils/auth";
import {getPermissionUserInfo} from "@/api/user";

export const useUserStore = defineStore('user', {
    state: () => ({
        username: '',
        userId: 0,
        avatar: '',
        roles: [] as string[],
    }),
    actions: {
        // 发送登录请求
        async login(data: LoginParams) {
            const loginResult = await login(data)
            console.log(loginResult)
            // 存储token
            setToken(loginResult.data)
            this.userId = loginResult.data.userId

            // 获取个人用户信息
            await this.getPermissionUserInfo()
        },

        async getPermissionUserInfo() {
            // 获取用户信息
            const res = await getPermissionUserInfo()
            console.log(res)
            this.roles = res.data.roles
            this.username = res.data.user.username
            this.avatar = res.data.user.avatar
        }
    }
})